<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>订单结算 - 花间村</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="{{ asset('css/wechat_service_account.css') }}">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background: #f8f9fa;
            color: #333;
            padding-bottom: 80px;
        }

        .container {
            max-width: 100%;
            padding: 15px;
        }

        .page-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }

        .cart-item {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            display: flex;
        }

        .cart-item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 15px;
        }

        .cart-item-info {
            flex: 1;
        }

        .cart-item-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
            color: #333;
        }

        .cart-item-price {
            font-size: 18px;
            color: #07C160;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .cart-item-quantity {
            font-size: 14px;
            color: #666;
        }

        .total-bar {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
        }

        .total-bar .total {
            color: #e63946;
        }

        .form-section {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 6px;
            color: #333;
            font-weight: 500;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
        }

        .submit-btn {
            background: #07C160;
            color: #fff;
            border: none;
            border-radius: 25px;
            padding: 12px 0;
            width: 100%;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            margin-top: 10px;
        }

        .submit-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .notification {
            position: fixed;
            bottom: 80px;
            left: 50%;
            transform: translateX(-50%);
            background: #07C160;
            color: white;
            padding: 12px 24px;
            border-radius: 30px;
            z-index: 300;
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
            animation: slideIn 0.3s ease-out;
            font-weight: 500;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translate(-50%, 20px);
            }

            to {
                opacity: 1;
                transform: translate(-50%, 0);
            }
        }
        
        /* 地址卡片样式 */
        .address-section {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 15px;
            color: #333;
        }
        
        .address-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid #eee;
        }
        
        .address-card:hover {
            background: #e9ecef;
            border-color: #ddd;
        }
        
        .address-card.selected {
            background: #d1f0dd;
            border-color: #07C160;
        }
        
        .address-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .address-title {
            font-size: 15px;
            font-weight: 500;
        }
        
        .default-tag {
            background: #07C160;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
        }
        
        .address-info {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
        }
        
        .address-detail {
            font-size: 13px;
            color: #666;
        }
        
        .no-address {
            text-align: center;
            color: #999;
            padding: 20px 0;
        }
        
        .add-address-btn {
            display: block;
            width: 100%;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 10px 0;
            font-size: 14px;
            cursor: pointer;
            text-align: center;
            text-decoration: none;
            margin-top: 10px;
        }
    </style>
<!--<script src="https://cdn.jsdelivr.net/npm/vconsole@latest/dist/vconsole.min.js"></script>-->
<!--    <script>new VConsole();</script>-->
</head>

<body>
    <div class="container">
        <div class="page-title">订单结算</div>
        @if($isDirectBuy && $directBuyProduct)
         <!-- 直接购买模式下的商品展示 -->
         @php
         $product = $directBuyProduct['product'];
         $quantity = $directBuyProduct['quantity'];
         $firstImage = $product['image_url'] ?? '/images/default-product.jpg';
         @endphp
         <div class="cart-item">
             <img src="{{ $firstImage }}" class="cart-item-image" alt="{{ $product['name'] }}" onerror="this.src='/images/default-product.jpg'">
             <div class="cart-item-info">
                 <div class="cart-item-title">{{ $product['name'] }}</div>
                 <div class="cart-item-price">¥{{ number_format($product['price'], 2) }}</div>
                 <div class="cart-item-quantity">数量：{{ $quantity }}</div>
             </div>
         </div>
        @elseif(!empty($cartData))
        <!-- 购物车结算模式下的商品展示 -->
        @foreach($cartData as $item)
        @php
        $images = $item['product']->images ?? [];
        $firstImage = count($images) > 0 ? $images[0] : ($item['product']->media->first() ? $item['product']->media->first()->getUrl() : $item['product']->image_url);
        @endphp
        <div class="cart-item">
            <img src="{{ $firstImage }}" class="cart-item-image" alt="{{ $item['product']->name }}" onerror="this.src='/images/default_product.jpg'" />
            <div class="cart-item-info">
                <div class="cart-item-title">{{ $item['product']->name }}</div>
                <div class="cart-item-price">¥{{ number_format($item['product']->price, 2) }}</div>
                <div class="cart-item-quantity">数量：{{ $item['quantity'] }}</div>
            </div>
        </div>
        @endforeach
        @else
        <!-- 空购物车情况 -->
        <div class="empty-cart-message" style="text-align:center;padding:50px 0;color:#999;">购物车为空，无法结算。</div>
        @endif
        <div class="total-bar">
            <span>商品金额</span>
            <span>¥{{ number_format($productTotalPrice, 2) }}</span>
        </div>
        
        <div class="total-bar">
            <span>运费</span>
            <span>
                @if($isFreeShipping)
                    <span style="color: #07C160;">免运费</span>
                @else
                    ¥{{ number_format($actualShippingFee, 2) }}
                @endif
                @if(!$isFreeShipping && $shippingFee > 0)
                    <small style="color: #999; font-size: 14px;">还差¥{{ number_format($freeShippingThreshold - $productTotalPrice, 2) }}免运费</small>
                @endif
            </span>
        </div>
        
        <!-- 配送提示信息 -->
        <div style="background-color: #fff7e6; border-radius: 12px; padding: 15px; margin-bottom: 20px; border-left: 4px solid #ff9800;">
            <p style="margin: 0; font-size: 18px; color: #e65100; line-height: 1.6;">
                每单满60元免运费！为保证商品质量，送货范围仅限沪苏浙皖地区，请您谅解！
            </p>
        </div>
        
        <div class="total-bar" style="background-color: #f8f0e3;">
            <span style="font-size: 18px; font-weight: bold;">实付金额</span>
            <span class="total" style="font-size: 20px;">¥{{ number_format($totalPrice, 2) }}</span>
        </div>
        
        <!-- 收货地址选择区域 -->
        <div class="address-section">
            <div class="section-title">收货地址</div>
            
            @if(isset($userAddresses) && $userAddresses->count() > 0)
                @foreach($userAddresses as $address)
                <div class="address-card" data-address-id="{{ $address->id }}" 
                     data-consignee="{{ $address->consignee }}" 
                     data-mobile="{{ $address->mobile }}" 
                     data-address="{{ $address->province }}{{ $address->city }}{{ $address->district }} {{ $address->address }}">
                    <div class="address-header">
                        <div class="address-title">{{ $address->consignee }}</div>
                        @if($address->is_default)
                        <span class="default-tag">默认</span>
                        @endif
                    </div>
                    <div class="address-info">{{ $address->mobile }}</div>
                    <div class="address-detail">{{ $address->province }}{{ $address->city }}{{ $address->district }} {{ $address->address }}</div>
                </div>
                @endforeach
            @else
                <div class="no-address">暂无收货地址</div>
            @endif
            
            <a href="{{ route('wechat.service.account.addresses') }}" class="add-address-btn">管理收货地址</a>
        </div>
        
        <form id="checkout-form" method="POST" action="{{ route('wechat.service.account.checkout.submit') }}">
            @csrf
            <div class="form-section">
                <div class="form-group">
                    <label class="form-label" for="receiver_name">收货人姓名</label>
                    <input class="form-input" type="text" id="receiver_name" name="receiver_name" required maxlength="20">
                </div>
                <div class="form-group">
                    <label class="form-label" for="receiver_address">收货地址</label>
                    <input class="form-input" type="text" id="receiver_address" name="receiver_address" required maxlength="100">
                </div>
                <div class="form-group">
                    <label class="form-label" for="receiver_phone">联系电话</label>
                    <input class="form-input" type="tel" id="receiver_phone" name="receiver_phone" required maxlength="20" pattern="[0-9\-\+ ]+">
                </div>
            </div>
            
            <div class="submit-section">
                @if($isDirectBuy && $directBuyProduct)
                    <button type="submit" class="submit-btn" id="direct-buy-submit-btn">确认下单</button>
                @else
                    @if(!empty($cartData))
                        <button type="submit" class="submit-btn">确认下单</button>
                    @else
                        <button type="submit" class="submit-btn disabled" disabled>确认下单</button>
                    @endif
                @endif
            </div>
        </form>
    </div>

    <!-- 载入底部导航栏 -->
    @include('wechat.service_account.components.bottom_nav')
    <style>
        /* 支付对话框样式 */
        .payment-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .payment-modal.show {
            display: flex;
        }

        .payment-dialog {
            background: #fff;
            border-radius: 12px;
            padding: 30px;
            margin: 20px;
            max-width: 300px;
            width: 100%;
            text-align: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .payment-dialog h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 18px;
        }

        .payment-dialog p {
            margin: 0 0 25px 0;
            color: #666;
            font-size: 14px;
            line-height: 1.5;
        }

        .payment-buttons {
            display: flex;
            gap: 10px;
        }

        .payment-btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }

        .payment-btn.primary {
            background: #07C160;
            color: #fff;
        }

        .payment-btn.primary:hover {
            background: #06AD56;
        }

        .payment-btn.secondary {
            background: #f8f9fa;
            color: #666;
            border: 1px solid #ddd;
        }

        .payment-btn.secondary:hover {
            background: #e9ecef;
        }
    </style>

    <!-- 支付对话框 -->
    <div id="paymentModal" class="payment-modal">
        <div class="payment-dialog">
            <h3>订单提交成功</h3>
            <p>您的订单已成功创建，请选择支付方式</p>
            <div class="payment-buttons">
                <!--<button type="button" class="payment-btn secondary" onclick="skipPayment()">暂不支付</button>-->
                <button type="button" class="payment-btn primary" onclick="startPayment()">立即支付</button>
            </div>
        </div>
    </div>

    <!-- 存储页面初始化数据 -->
    <div id="page-data" data-is-direct-buy="{{ $isDirectBuy ? 'true' : 'false' }}" data-direct-buy-product="{{ json_encode($directBuyProduct ?? null) }}" data-default-address-id="{{ isset($userAddresses) && $userAddresses->count() > 0 ? ($userAddresses->firstWhere('is_default', true) ?? $userAddresses->first())->id : 'null' }}"></div>
    
    <script>
        // 为表单添加提交前的处理
        document.addEventListener('DOMContentLoaded', function() {
            // 从HTML数据属性读取初始化数据
            const pageData = document.getElementById('page-data');
            window.isDirectBuy = pageData.dataset.isDirectBuy === 'true';
            window.directBuyProduct = JSON.parse(pageData.dataset.directBuyProduct || 'null');
            
            // 添加调试日志
            console.log('页面初始化数据:', { isDirectBuy: window.isDirectBuy, directBuyProduct: window.directBuyProduct });
            
            const checkoutForm = document.getElementById('checkout-form');
            if (checkoutForm) {
                checkoutForm.addEventListener('submit', function(event) {
                    if (window.isDirectBuy && window.directBuyProduct) {
                        console.log('表单提交中，确保包含直接购买信息');
                        
                        // 移除现有的直接购买字段
                        const removeFields = (names) => {
                            names.forEach(name => {
                                const field = checkoutForm.querySelector(`input[name="${name}"]`);
                                if (field) field.remove();
                            });
                        };
                        removeFields(['direct_buy', 'product_id', 'quantity']);
                        
                        // 添加新的直接购买字段
                        const addField = (name, value) => {
                            const input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = name;
                            input.value = value;
                            checkoutForm.appendChild(input);
                            console.log(`添加字段: ${name} = ${value}`);
                        };
                        
                        addField('direct_buy', '1');
                        addField('product_id', window.directBuyProduct.product.id);
                        addField('quantity', window.directBuyProduct.quantity);
                    }
                    console.log('表单提交完成');
                });
            }
            
            // 如果是直接购买模式，进行页面处理
            if (window.isDirectBuy && window.directBuyProduct) {
                // 隐藏购物车为空的提示信息
                const emptyCartMessage = document.querySelector('.empty-cart-message');
                if (emptyCartMessage) {
                    emptyCartMessage.style.display = 'none';
                }
                
                // 确保提交按钮可见并可用
                const submitButton = document.querySelector('#checkout-form button[type="submit"]');
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.classList.remove('disabled');
                }
            }
            
            // 初始化地址选择功能
            // 为所有地址卡片添加点击事件
            const addressCards = document.querySelectorAll('.address-card');
            console.log('找到地址卡片数量:', addressCards.length);
            addressCards.forEach(card => {
                card.addEventListener('click', function() {
                    console.log('点击了地址卡片');
                    // 移除所有选中状态
                    addressCards.forEach(c => c.classList.remove('selected'));
                    
                    // 添加选中状态到当前地址
                    this.classList.add('selected');
                    
                    // 获取地址信息并填充到表单
                    const consignee = this.getAttribute('data-consignee');
                    const mobile = this.getAttribute('data-mobile');
                    const address = this.getAttribute('data-address');
                    
                    console.log('地址信息:', { consignee, mobile, address });
                    
                    const receiverName = document.getElementById('receiver_name');
                    const receiverPhone = document.getElementById('receiver_phone');
                    const receiverAddress = document.getElementById('receiver_address');
                    
                    console.log('表单元素:', { receiverName, receiverPhone, receiverAddress });
                    
                    if (receiverName && receiverPhone && receiverAddress) {
                        receiverName.value = consignee || '';
                        receiverPhone.value = mobile || '';
                        receiverAddress.value = address || '';
                        console.log('已填充表单');
                    } else {
                        console.log('未找到表单元素');
                    }
                });
            });
            
            // 如果存在默认地址，自动选择
            // 从data属性中读取默认地址ID
            var defaultAddressId = null;
            try {
                // 直接使用已声明的pageData变量，避免重复声明
                if (pageData && pageData.dataset.defaultAddressId && pageData.dataset.defaultAddressId !== 'null') {
                    defaultAddressId = parseInt(pageData.dataset.defaultAddressId);
                    if (!isNaN(defaultAddressId)) {
                        setTimeout(function() { selectAddress(defaultAddressId); }, 100);
                    }
                }
            } catch (e) {
                console.log('处理默认地址时出错:', e);
            }
        });
        
        // 页面可见性变化时，处理直接购买数据
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden && window.isDirectBuy && window.directBuyProduct) {
                console.log('页面变为可见，确保商品信息显示');
            }
        });
        
        // 通知函数
        function showNotification(message) {
            // 移除已存在的通知
            const existingNotification = document.querySelector('.notification');
            if (existingNotification) {
                existingNotification.remove();
            }
            
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = 'notification';
            notification.textContent = message;
            document.body.appendChild(notification);
            
            // 3秒后自动消失
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 3000);
        }
        
        // 保持向后兼容的selectAddress函数
        function selectAddress(addressId) {
            const addressCard = document.querySelector(`.address-card[data-address-id="${addressId}"]`);
            if (addressCard) {
                addressCard.click();
            }
        }

        let currentPrepayId = null;
        let currentOrderId = null;

        // 表单提交逻辑
        const form = document.getElementById('checkout-form');
        if (form) {
            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                const btn = form.querySelector('.submit-btn');
                btn.disabled = true;
                btn.textContent = '提交中...';

                try {
                    // 准备提交数据
                    const submitData = {
                        receiver_name: form.receiver_name.value,
                        receiver_address: form.receiver_address.value,
                        receiver_phone: form.receiver_phone.value,
                    };
                    
                    // 如果是直接购买模式，添加直接购买的商品信息
                    if (isDirectBuy && directBuyProduct) {
                        console.log('提交直接购买数据:', directBuyProduct);
                        submitData.direct_buy = true;
                        submitData.product_id = directBuyProduct.product_id;
                        submitData.quantity = directBuyProduct.quantity;
                        if (directBuyProduct.variant_id) {
                            submitData.variant_id = directBuyProduct.variant_id;
                        }
                        // 确保不使用购物车数据
                        submitData.use_cart = false;
                    } else {
                        // 普通购物车结算
                        submitData.use_cart = true;
                    }
                    
                    const response = await fetch(form.action, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        },
                        body: JSON.stringify(submitData),
                    });

                    const data = await response.json();
                    if (data.success) {
                        // 保存prepay_id和订单ID
                        currentPrepayId = data.prepay_id;
                        currentOrderId = data.order_id;

                        // 显示支付对话框
                        showPaymentModal();
                    } else {
                        alert(data.message || '下单失败，请重试');
                        btn.disabled = false;
                        btn.textContent = '确认下单';
                    }
                } catch (error) {
                    console.error('提交失败:', error);
                    alert('网络错误，请重试');
                    btn.disabled = false;
                    btn.textContent = '确认下单';
                }
            });
        }

        // 显示支付对话框
        function showPaymentModal() {
            const modal = document.getElementById('paymentModal');
            modal.classList.add('show');
        }

        // 隐藏支付对话框
        function hidePaymentModal() {
            const modal = document.getElementById('paymentModal');
            modal.classList.remove('show');
        }

        // 暂不支付
        function skipPayment() {
            hidePaymentModal();
            // 跳转到订单页面
            window.location.href = "{{ route('wechat.service.account.orders.list') }}";
        }

        async function startPayment() {
            hidePaymentModal();
            if (currentPrepayId) {
                console.log('开始支付，prepay_id:', currentPrepayId);
                try {
                    // 实时获取JS配置
                    const response = await fetch("{{ route('wechat.service.account.checkout.get-js-config') }}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        },
                        body: JSON.stringify({
                            prepay_id: currentPrepayId,
                        }),
                    });

                    const data = await response.json();
                    if (data.success) {
                        console.log('获取到JS配置:', data.js_config);
                        initiatePayment(data.js_config);
                    } else {
                        console.error('获取JS配置失败:', data.message);
                        alert('支付配置获取失败：' + data.message);
                        window.location.href = "{{ route('wechat.service.account.orders.list') }}";
                    }
                } catch (error) {
                    console.error('获取JS配置异常:', error);
                    alert('网络错误，请重试');
                    window.location.href = "{{ route('wechat.service.account.orders.list') }}";
                }
            } else {
                console.error('prepay_id为空');
                alert('支付信息获取失败，请重试');
                window.location.href = "{{ route('wechat.service.account.orders.list') }}";
            }
        }

        function initiatePayment(paymentData) {
            console.log('=== 开始调用微信支付 ===');
            console.log('支付参数详情:', JSON.stringify(paymentData, null, 2));
            console.log('当前环境是否支持WeixinJSBridge:', typeof WeixinJSBridge !== 'undefined');
            console.log('当前环境是否支持WeixinJSBridge.invoke:', typeof WeixinJSBridge !== 'undefined' && typeof WeixinJSBridge.invoke !== 'undefined');
            console.log('当前URL:', window.location.href);
            console.log('User Agent:', navigator.userAgent);

            // 增强支付参数校验
            const requiredParams = ['appId', 'timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
            const missingParams = requiredParams.filter(param => !paymentData[param]);
            if (missingParams.length > 0) {
                console.error('缺少必要支付参数:', missingParams);
                alert('支付配置不完整，缺少参数: ' + missingParams.join(','));
                return;
            }
            
            // 严格验证时间戳(5分钟内有效)
            const now = Math.floor(Date.now() / 1000);
            const timestampDiff = now - parseInt(paymentData.timeStamp);
            if (isNaN(timestampDiff) || timestampDiff > 300) {
                console.error('时间戳无效或已过期:', paymentData.timeStamp, '当前:', now);
                alert('支付已超时，请刷新页面重新下单');
                return;
            }
            
            // 验证package格式
            if (!paymentData.package || !paymentData.package.startsWith('prepay_id=')) {
                console.error('package格式错误:', paymentData.package);
                alert('支付参数异常，请重试');
                return;
            }
            
            // 验证签名类型
            if (paymentData.signType !== 'RSA' && paymentData.signType !== 'MD5') {
                console.error('不支持的签名类型:', paymentData.signType);
                alert('支付配置异常，请重试');
                return;
            }

            if (typeof WeixinJSBridge === 'undefined') {
                console.error('WeixinJSBridge未定义');
                alert('请在微信浏览器中打开支付');
                return;
            }

            if (typeof WeixinJSBridge.invoke === 'undefined') {
                console.error('WeixinJSBridge.invoke方法不存在');
                alert('微信支付接口不可用，请重试');
                return;
            }

            console.log('准备调用WeixinJSBridge.invoke...');
            
            WeixinJSBridge.invoke('getBrandWCPayRequest', paymentData, function(res) {
                console.log('=== 微信支付回调结果 ===');
                console.log('完整回调对象:', res);
                console.log('err_msg:', res.err_msg);
                console.log('err_desc:', res.err_desc);
                console.log('err_code:', res.err_code);

                if (res.err_msg === 'get_brand_wcpay_request:ok') {
                    // 支付成功
                    console.log('支付成功！');
                    alert('支付成功！');
                    window.location.href = "{{ route('wechat.service.account.orders.list') }}";
                } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                    // 支付取消
                    console.log('支付已取消');
                    alert('支付已取消');
                    window.location.href = "{{ route('wechat.service.account.orders.list') }}";
                } else {
                    // 支付失败
                    console.error('支付失败，详细错误信息:', {
                        err_msg: res.err_msg,
                        err_desc: res.err_desc,
                        err_code: res.err_code
                    });
                    
                    let errorMessage = '支付失败';
                    if (res.err_desc) {
                        errorMessage += ': ' + res.err_desc;
                    } else if (res.err_msg) {
                        errorMessage += ': ' + res.err_msg;
                    }
                    
                    alert(errorMessage);
                    window.location.href = "{{ route('wechat.service.account.orders.list') }}";
                }
            });
        }
    </script>
</body>

</html>